import * as userApi from '../../api/user';

export default {
  namespaced: true,
  state() {
    return {
      // 账号登录信息
      info: JSON.parse(localStorage.getItem('userInfo')) || {},
      // 短信登录信息
      codeInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
      // 验证码
      code: {},
    };
  },
  mutations: {
    // 账号登录信息
    SET_INFO(state, newValue) {
      state.info = newValue;
    },
    // 短信登录信息
    SET_CODE_INFO(state, newValue) {
      state.codeInfo = newValue;
    },
    // 验证码
    SET_CODE(state, newValue) {
      state.code = newValue;
    },
  },
  actions: {
    // 账号登录信息
    async login({ commit }, params) {
      const pageRes = {
        success: false,
        msg: '',
      };
      await userApi.login(params)
        .then((res) => {
          pageRes.success = true;
          pageRes.msg = res.msg;
          commit('SET_INFO', res.result);
        })
        .catch((err) => {
          pageRes.success = false;
          pageRes.msg = err.message;
        });
      return pageRes;
    },
    // 短信登录信息
    async codeLogin({ commit }, params) {
      const pageRes = {
        success: false,
        msg: '',
      };
      await userApi.codeLogin(params)
        .then((res) => {
          pageRes.success = true;
          pageRes.msg = res.msg;
          commit('SET_CODE_INFO', res.result);
        })
        .catch((err) => {
          pageRes.success = false;
          pageRes.msg = err.message;
        });
      return pageRes;
    },
    // 验证码
    async updateCode({ commit }, params) {
      const pageRes = {
        success: false,
        msg: '',
      };
      await userApi.getCode(params)
        .then((res) => {
          pageRes.success = true;
          pageRes.msg = res.msg;
          commit('SET_CODE', res.result);
        })
        .catch((err) => {
          pageRes.success = false;
          pageRes.msg = err.message;
        });
      return pageRes;
    },
  },
};
